import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/components/common/Layout'
import Notfound from '@/components/common/Notfound'
import Login from '@/components/pages/Login'
import Product from '@/components/pages/Product'
import Admin from '@/components/pages/Admin'
import Wxuser from '@/components/pages/Wxuser'
import Case from '@/components/pages/Case'
import Article from '@/components/pages/Article'
import Like from '@/components/pages/Like'
import Collect from '@/components/pages/Collect'
import Share from '@/components/pages/Share'
import Comment from '@/components/pages/Comment'
import PDFLog from '@/components/pages/PDFLog'

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      meta: { title: '登录-微信小程序后台-黎明重工' }, // 标题保存在meta.title中，由路由beforeEach实现title切换
      component: Login
    },
    {
      path: '*',
      name: '404',
      component: Notfound
    },
    {
      path: '/pdf-log',
      meta: { requireAuth: true, title: 'pdf 访问记录' },
      component: PDFLog,
      name: 'PDFLog'
    },
    {
      path: '/admin',
      component: Layout,
      meta: {
        requireAuth: true
      },
      children: [
        { path: '/', component: Product, name: 'index', meta: { title: '产品管理' } },
        { path: 'auser', component: Admin, name: 'auser', meta: { title: '管理员列表' } },
        { path: 'Wxuser', component: Wxuser, name: 'wxuser', meta: { title: '微信用户' } },
        { path: 'Case', component: Case, name: 'case', meta: { title: '案例管理' } },
        { path: 'Article', component: Article, name: 'article', meta: { title: '文章列表' } },
        { path: 'Like', component: Like, name: 'like', meta: { title: '点赞列表' } },
        { path: 'Collect', component: Collect, name: 'collect', meta: { title: '收藏列表' } },
        { path: 'Share', component: Share, name: 'share', meta: { title: '转发列表' } },
        { path: 'Comment', component: Comment, name: 'comment', meta: { title: '评论列表' } }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  let nowTime = Number.parseInt(Date.now() / 1000)

  if (to.matched.some(r => r.meta.requireAuth)) {
    if (token && (nowTime < localStorage.getItem('expire') + localStorage.getItem('token_time'))) {
      next()
    } else {
      localStorage.clear()
      next({path: '/'})
    }
  } else {
    next()
  }
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

export default router
